const fs = require("fs/promises");
const path = require("path");
const BaseService = require("../base");

class TrademarksService extends BaseService {
  async getAllTrademarkList() {
    const ctx = this.ctx;
    const trademarks = await ctx.model.Product.Trademarks.find().sort({ name: 1 });
    return this.toId(trademarks, ["isAdmin"]);
  }
  async getTrademarkList({ page, limit }) {
    const ctx = this.ctx;
    const trademarks = await ctx.model.Product.Trademarks.find({})
      .skip((page - 1) * limit)
      .limit(limit);

    const total = await ctx.model.Product.Trademarks.countDocuments();

    return this.toId(
      {
        records: trademarks,
        total,
      },
      ["isAdmin"]
    );
  }
  async saveTrademark(trademark) {
    const ctx = this.ctx;
    await ctx.model.Product.Trademarks.create(trademark);
    return null;
  }
  async updateTrademark(trademark) {
    const ctx = this.ctx;
    const tm = await ctx.model.Product.Trademarks.findOne({ _id: trademark.id, isAdmin: false });
    if (!tm) return false;
    tm.name = trademark.name;
    tm.logoUrl = trademark.logoUrl;
    await tm.save();
    return true;
  }
  async removeTrademark(id) {
    const ctx = this.ctx;
    const tm = await ctx.model.Product.Trademarks.findOne({ _id: id, isAdmin: false });
    if (!tm) return false;
    // 删除品牌图片
    const logoUrl = tm.logoUrl.replace(`http://${ctx.header.host}/`, "");
    const imgPath = path.resolve(__dirname, "../../", logoUrl);
    await fs.rm(imgPath);
    // 删除品牌
    await ctx.model.Product.Trademarks.deleteOne({ _id: id });
    return true;
  }
}

module.exports = TrademarksService;
